<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="位置" prop="node">
        <el-select v-model="queryParams.node" placeholder="请选择" @change="getListType">
          <el-option
            v-for="item in optionsArea"
            :key="item.id"
            :label="item.areaName"
            :value="item.id">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentType">
        <el-select v-model="queryParams.equipmentType" placeholder="请选择" @change="getListGroup">
          <el-option
            v-for="item in optionsType"
            :key="item.id"
            :label="item.typeName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="dept">
        <el-select v-model="queryParams.dept" placeholder="请选择" >
          <el-option
            v-for="item in optionsGroup"
            :key="item.id"
            :label="item.equipmentGroupName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

      <el-form-item>
        <el-button size="mini" @click="openDialog">早晚时间设置</el-button>
      </el-form-item>
    </el-form>


    <el-descriptions class="margin-top"  :column="3"  border>
      <el-descriptions-item  v-for="(items, indexs) in equipmentList" :key="indexs">
        <div class="app-container" style="background: #bfbfbf">
          <el-row >
            <el-col :span="12"><h3 class="title">{{items.title}}</h3></el-col>
            <el-col :span="12"><h6 class="title" >更新时间：{{eTime[indexs]}}</h6></el-col>
          </el-row>
          <el-row :gutter="10" v-for="(item, index) in items.list" :key="index">
            <div style="display:flex;align-items: center;" v-if="item.name!=='风向'">
              <el-col :span="6"><el-input v-model="item.name" readonly/></el-col>
              <el-col :span="9" style="display: flex;align-items: center"><span style="display:inline-block;width:140px">{{ item.name=='空气温度'?'白天最大值:':'最大值:' }}</span><el-input v-model="item.vMax" placeholder="请输入最大值"/></el-col>
              <el-col :span="9" style="display: flex;align-items: center"><span style="display:inline-block;width:140px">{{ item.name=='空气温度'?'白天最小值:':'最小值:' }}</span><el-input v-model="item.vMin" placeholder="请输入最小值"/></el-col>
            </div>
            <div style="display:flex;align-items: center;" v-if="item.name=='空气温度'">
              <el-col :span="6"><el-input value="空气温度" readonly></el-input></el-col>
              <el-col :span="9" style="display: flex;align-items: center"><span style="display:inline-block;width:140px">夜晚最大值:</span><el-input v-model="item.nMax" placeholder="请输入最大值"/></el-col>
              <el-col :span="9" style="display: flex;align-items: center"><span style="display:inline-block;width:140px">夜晚最小值:</span><el-input v-model="item.nMin" placeholder="请输入最小值"/></el-col>
            </div>
          </el-row>
          <el-row style="margin-top: 10px;display: flex;justify-content: flex-end">
            <!-- <el-button icon="el-icon-edit" size="mini">编辑</el-button> -->
            <el-button type="primary" icon="el-icon-check" size="mini" @click="handleSave(items)">保存</el-button>
          </el-row>
        </div>
      </el-descriptions-item>

    </el-descriptions>

    <!-- 弹窗 -->
    <el-dialog title="早晚时间设置" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="白天时间范围" prop="startTime">
          <el-time-picker
            is-range
            arrow-control
            v-model="form.startTime"
            format="HH:mm"
            value-format="HH:mm"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="晚上时间范围" prop="endTime">
          <el-time-picker
            is-range
            arrow-control
            format="HH:mm"
            value-format="HH:mm"
            v-model="form.endTime"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围">
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEquipmentByGruop,setMinMax,setTime,getTimeEnd} from "@/api/iot/equipment";
import { listTypeByArea} from "@/api/iot/type";
import { listAreaAll} from "@/api/iot/area";
import { listGroupAll} from "@/api/iot/group";
import mqtt from 'mqtt'
import { MQTT_SERVICE, MQTT_USERNAME, MQTT_PASSWORD,formatDate } from '@/utils/index'
import {getTime} from "../../utils/ruoyi";

export default {
  name: "Equipment",
  data() {
    return {
      // 遮罩层
      loading: true,
      client:null,
      options:{
        connectTimeout: 40000,
        clientId: 'mqtitId-Home',
        username: MQTT_USERNAME,
        password: MQTT_PASSWORD,
        keepAliveInterval: 10,//当时间为60时会出现断链问题
        clean: true
      },
      areaId: 1,
      eData:[],
      eTime:[],
      mqttData:[],
      optionsArea:[],
      optionsType:[],
      optionsGroup:[],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      equipmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        equipmentType: null,
        describe: null,
        dept: null,
        address: null,
        gateway: null,
        status: null,
        node: null,
        analog: null,
        offset: null
      },
      form:{}
    };
  },
  created() {
    this.client = mqtt.connect(MQTT_SERVICE, this.options)
    this.getList();
    this.getListArea();
    this.mqttMSG();
  },
  methods: {
    openDialog(){
      this.open=true
      getTimeEnd().then(response => {
        let date = JSON.parse(response.msg)
        // this.form.startTime=[date.startDateMin,date.startDateMax]
        // this.form.endTime=[date.endDateMin,date.endDateMax]
        this.$set(this.form, 'startTime', [date.startDateMin,date.startDateMax]);
        this.$set(this.form, 'endTime', [date.endDateMin,date.endDateMax]);
      })
    },
    submitForm(){
      let data = {
        startDateMax:this.form.startTime[1],
        startDateMin:this.form.startTime[0],
        endDateMax:this.form.endTime[1],
        endDateMin:this.form.endTime[0],
      }
      setTime(data).then(response => {
        this.$message.success(response.msg);
        this.open=false
      })
    },
    cancel(){
      this.open=false
    },
    handleSave(item){
      let data = {
        id:item.id,
        vMax:'',
        vMin:'',
        nMax:'',
        nMin:'',
      }
      let max=[]
      let min=[]
      let nmax=[]
      let nmin=[]
      item.list.forEach(element => {
        max.push(element.vMax)
        min.push(element.vMin)
        nmax.push(element.nMax)
        nmin.push(element.nMin)
      });
      data.vMax=max.join(',')
      data.vMin=min.join(',')
      data.nMax=nmax.join(',')
      data.nMin=nmin.join(',')
      setMinMax(data).then(response => {
        this.$message.success(response.msg);
        this.getList()
      })
    },
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listEquipmentByGruop(this.queryParams).then(response => {
        this.equipmentList = this.filteredNestedArray(response.rows)
      });
    },
    filteredNestedArray(list) {
      return list.filter(parent => {
        const isHide = parent.list.length == 1 && parent.list[0]?.name == '风向';
        return !isHide;
      });
    },
    /** 查询区域列表 */
    getListArea() {
      this.loading = true;
      listAreaAll(this.queryParams).then(response => {
        this.optionsArea = response.rows;
        this.loading = false;

      });
    },
    /** 查询区域列表 */
    getListType(areaId) {
      this.areaId=areaId;
      this.optionsType =[];
      this.loading = true;
      listTypeByArea(areaId).then(response => {
        this.optionsType = response.rows;
        this.loading = false;

      });
    },
    /** 查询区域列表 */
    getListGroup(typeId) {
      this.loading = true;
      this.optionsGroup=[];
      listGroupAll(typeId,this.areaId).then(response => {
        this.optionsGroup = response.rows;
        this.loading = false;

      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    mqttMSG () {
      // mqtt连接
      this.client.on('connect', (e) => {
        this.loading = false;
        console.log('连接成功:')
        this.client.subscribe('equipment', { qos: 0 }, (error) => {
          if (!error) {
            console.log('订阅成功')
          } else {
            console.log('订阅失败')
          }
        })
      })
      // 接收消息处理
      this.client.on('message', (topic, message) => {
        let mqttDatas=JSON.parse(message);
        for (let i = 0; i < this.equipmentList.length; i++) {
          for (let j = 0; j < this.equipmentList[i].list.length; j++) {
            let name=this.equipmentList[i].list[j].name;
            let node=this.equipmentList[i].list[j].node;
            let id=this.equipmentList[i].list[j].id;
            let gateway=this.equipmentList[i].list[j].gateway;
            let analog=this.equipmentList[i].list[j].analog;
            let offset=this.equipmentList[i].list[j].offset;
            let unit=this.equipmentList[i].list[j].unit;
            if (mqttDatas.gateway=="10042317"){  }
            if (mqttDatas.gateway=="10042317"){  }
            if (node==mqttDatas.nodeId && gateway==mqttDatas.gateway){
              if (mqttDatas.gateway=="10042319"){  }
              this.eTime[i]=getTime();
              this.$set(this.eTime,i,getTime());
              if (analog=="gz"){
                this.$set(this.eData,id,Number(offset)*Number(mqttDatas.gz)+" "+unit);
              }
              if (analog=="tem"){
                if(name=='风向'){
                  if (mqttDatas.tem==0){
                    this.$set(this.eData,id,"北风");
                  }
                  if(0<mqttDatas.tem<90){
                    this.$set(this.eData,id,"东北风");
                  }
                  if (mqttDatas.tem==90){
                    this.$set(this.eData,id,"东风");
                  }
                  if (90<mqttDatas.tem<180){
                    this.$set(this.eData,id,"东南风");
                  }
                  if (mqttDatas.tem==180){
                    this.$set(this.eData,id,"南风");
                  }
                  if (180<mqttDatas.tem<270){
                    this.$set(this.eData,id,"西南风");
                  }
                  if (mqttDatas.tem==270){
                    this.$set(this.eData,id,"西风");
                  }
                  if (270<mqttDatas.tem<360){
                    this.$set(this.eData,id,"西北风");
                  }
                }else{
                  this.$set(this.eData,id,(Number(offset)*Number(mqttDatas.tem)).toFixed(2)+" "+unit);
                }
              }
              if (analog=="hum"){
                this.$set(this.eData,id,(Number(offset)*Number(mqttDatas.hum)).toFixed(2)+" "+unit);
                if (id=="538"&&node=="2"){
                  if (mqttDatas.hum=="0"){
                    this.$set(this.eData,id,"北风");
                  }
                  if (mqttDatas.hum=="0.1"){
                    this.$set(this.eData,id,"东北风");
                  }
                  if (mqttDatas.hum=="0.2"){
                    this.$set(this.eData,id,"东风");
                  }
                  if (mqttDatas.hum=="0.3"){
                    this.$set(this.eData,id,"东南风");
                  }
                  if (mqttDatas.hum=="0.4"){
                    this.$set(this.eData,id,"南风");
                  }
                  if (mqttDatas.hum=="0.5"){
                    this.$set(this.eData,id,"西南风");
                  }
                  if (mqttDatas.hum=="0.6"){
                    this.$set(this.eData,id,"西风");
                  }
                  if (mqttDatas.hum=="0.7"){
                    this.$set(this.eData,id,"西北风");
                  }
                }

              }
            }
          }
        }
        this.msg = message.toString()
      })
      // 断开发起重连
      this.client.on('reconnect', (error) => {
        console.log('正在重连:', error)
      })
      // 链接异常处理
      this.client.on('error', (error) => {
        console.log('连接失败:', error)
      })
      // this.client.on('close',()=>{
      //   this.client.end;
      // })
    }


  }
};
</script>
<style>
.title {
  margin: 0px auto 30px auto;
  text-align: left;
  color: #000000;
}
</style>
